
from xml.sax import handler, make_parser

class StyleSheetsReaderImpl(handler.ContentHandler):
    def __init__(self, other):
        self.data = {}    # stored styles (sid based)
        self.sid  = None  # last id of style
        self.aid  = None  # last id of attribute

        if not other == None:
            self.data = other.data.copy()

    def getAttributes(self, key):
        attributes = {}
        if key.find(".") >= 0:
            masterKey = key.split(".")[0]
            if self.data.has_key(masterKey):
                for akey, avalue in self.data[masterKey].items():
                    attributes[akey] = avalue

        if self.data.has_key(key):
            for akey, avalue in self.data[key].items():
                attributes[akey] = avalue

        return attributes

    def startElement(self, name, attr):
        if name == "stylesheets":
            return

        if name == "style":
            try:
                self.sid            = attr["id"]
                self.data[self.sid] = {}
            except:
                pass
            return

        try:
            self.aid = attr["id"]
        except:
            pass

    def characters(self, text):
        if not self.sid == None and \
           not self.aid == None:
            value = text
            if self.aid == "font":
                symbols = text.split(",")
                if len(symbols) == 3:
                    value = (symbols[0].strip(), \
                             int(symbols[1].strip()), \
                             symbols[2].strip())
            self.data[self.sid][self.aid] = value

    def endElement(self, name):
        if name == "stylesheets":
            return

        if not self.aid == None:
            self.aid = None
            return

        if not self.sid == None:
            self.sid = None
            return

    def parse(self, pathAndFileName):
        parser = make_parser()
        parser.setContentHandler(self)
        parser.parse(pathAndFileName)

